package com.chenjiaru.thread.lock.deadlock;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 死锁案例：不同的线程分别占用对方需要的同步资源不放弃，都在等待对方放弃自己需要的同步资源，就形成了线程的死锁
 */
@Data
@Slf4j
public class DeadLock {

    public static void main(String[] arr) {
        String cat = "cat";
        String dog = "dog";

        new Thread(() -> {
            try {
                synchronized(cat){
                    log.info("抱抱{}", cat);
                    Thread.sleep(2000);
                    synchronized(dog){
                        log.info("抱抱{}", dog);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                synchronized(dog){
                    log.info("抱抱{}", dog);
                    Thread.sleep(2000);
                    synchronized(cat){
                        log.info("抱抱{}", cat);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

}
